// pages/modify/modify.js
import {
  config
} from '../../utils/config';

import {
  UserModel
} from '../../models/user.js';

import {
  Token
} from '../../utils/token.js';

const token = new Token();

const user = new UserModel();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: {},
    nickName: '',
    description: '',
    avatarUrl: '',
    saveBtnStatus: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    token.verify().then(res => {
      if (res) {
        this._loadData();
      }
    });
  },

  _loadData() {
    user.getUserInfo().then(res => {
      this.setData({
        user: res.data
      })
    });
  },

  onMaxTxt(e) {
    let description = e.detail.value;
    this.setData({
      description
    })
    this._onChangeBtnStatus();
  },
  onInput(e) {
    let nickName = e.detail.value;
    this.setData({
      nickName
    })
    this._onChangeBtnStatus();
  },
  _onChangeBtnStatus() {
    if (this.data.nickName === '' && this.data.description === '' && this.data.avatarUrl === '') {
      this._closeBtn();
    } else {
      this._openBtn();
    }
  },
  onChangeAvatar() {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        that._openBtn();
        that.setData({
          avatarUrl: res.tempFilePaths[0]
        })
      }
    })
  },
  onBlur() {
    let nickName = this.data.nickName;
    if (nickName && nickName !== '') {
      user.check(nickName).then(res => {
        if (!res.data) {
          this._closeBtn();
          this._show_tip('昵称已经存在了，请换一个吧～');
        } else {
          this._openBtn();
        }
      })
    }
  },
  _saveWithFile() {

  },
  // onSave() {
  //   let that = this;
  //   if (!that.data.newAvatarUrl && !that.data.newDescription && !that.data.newNickName) {
  //     return;
  //   }

  //   that.data.user.nickName = that.data.newNickName;
  //   that.data.user.description = that.data.newDescription;

  //   console.log(!that.data.newAvatarUrl);

  //   wx.uploadFile({
  //     url: config.baseUrl + 'user/modify', //
  //     filePath: that.data.newAvatarUrl,
  //     name: 'avatarFile',
  //     header: {
  //       'content-type': 'multipart/form-data'
  //     },
  //     formData: {
  //       "token": wx.getStorageSync('token'),
  //       "nickName": that.data.newNickName,
  //       "description": that.data.newDescription
  //     },
  //     success: (res) => {
  //       console.log(res);
  //       const code = res.statusCode.toString();
  //       if (code.startsWith('2')) {
  //         that._show_tip('修改成功');
  //         setTimeout(() => {
  //           wx.navigateBack({ //返回
  //             delta: 1
  //           })
  //         }, 900);
  //       } else {
  //         console.log(1);
  //         that._show_tip();
  //       }
  //     },
  //     fail: (err) => {
  //       console.log(err);
  //       console.log(2);
  //       that._show_tip();
  //     }
  //   });
  // },
  onSave() {
    let that = this;
    that.data.user.nickName = that.data.nickName;
    that.data.user.description = that.data.description;
    if (!that.data.saveBtnStatus) {
      if (that.data.avatarUrl && that.data.avatarUrl !== '') {
        // 附带文件上传
        user.modifyWithFile(config.baseUrl, that.data.avatarUrl, that.data.user).then(res => {
          if (!res.data.result) {
            that._show_tip(res.data.msg);
          } else {
            that._show_tip('修改成功');
            setTimeout(() => {
              wx.navigateBack({ //返回
                delta: 1
              })
            }, 900);
          }
        });
      } else {
        // 单纯保存文本
        user.modify(that.data.user).then(res => {
          if (res.data.result) {
            that._show_tip(res.data.msg);
            setTimeout(() => {
              wx.navigateBack({ //返回
                delta: 1
              })
            }, 900);
          } else {
            that._show_tip(res.data.msg);
          }
        })
      }
    }
  },
  _show_tip(msg = '修改个人信息失败') {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 2000
    });
  },
  _openBtn() {
    this.setData({
      saveBtnStatus: false
    })
  },
  _closeBtn() {
    this.setData({
      saveBtnStatus: true
    })
  }
})